package com.yc.forum.dao;

import com.yc.forum.util.DBHelper;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;

public class PostDao {
    //获取回复帖的数量
    public int selectPostSum(String problemId){
        String sql="select * from post where problemkey=?";

        return Integer.parseInt(String.valueOf(DBHelper.count(sql,problemId)));
    }
    /**
     * 存入一条帖子
     * @param title     帖子标题
     * @param headImg   帖子封面
     * @param keyword   帖子查询关键字（在查询界面可根据关键字查询）
     * @param account   发帖人账号
     * @param module    帖子发布模块
     * @param privateLevel  私密等级（0个人可看，1关注可看，2进入个人主页可看，3公开）
     * @param body      帖子主体
     * @param problemKey    是否为问题的回答，是空则不是问题的回答，默认为null
     */
    public int saveOnePost(String title,String headImg,String keyword,String account,String module,
                            int privateLevel,String body,String problemKey){
        System.out.println("----------------init saveOnePostDao----------------");
        String sql="insert into post(title,img,keyword,account,module,privatelevel,body,problemkey) " +
                " values(?,?,?,?,?,?,?,?)";
        List<Object> params=new ArrayList<Object>();
        params.add(title);
        //头像判空
        if(headImg.isEmpty()||headImg.equals("")) {
            headImg = null;
        }
        params.add(headImg);
        params.add(keyword);
        params.add(account);
        params.add(module);
        params.add(privateLevel);
        params.add(body);
        params.add(problemKey);
        return DBHelper.update(sql,params.toArray());
    }
    //分模块 分页查询 帖子
    public Map<String,Object> selectClassify(String module,String page,String size,String search){
        String sql;
        if(search==null||search.isEmpty()){
            sql="select * from post where module = ? order by begintime DESC";
        }else{
            sql="select * from post where title like ? or keyword like ? or body like ? order by begintime DESC";
            search="%"+search+"%";
        }
        int start=(Integer.parseInt(page)-1)*Integer.parseInt(size);
        String pagesql=sql+" limit "+start+","+size+"";
        System.out.println("分页查询pagesql==============="+pagesql);
        List<Map<String, Object>> list;
        long total;
        if(search==null||search.isEmpty()) {
            list = DBHelper.selectListMap(pagesql, module);
            total=DBHelper.count(sql,module);
        }else{
            list = DBHelper.selectListMap(pagesql, search,search,search);
            total=DBHelper.count(sql,search,search,search);
        }
        Map<String,Object> map=new HashMap<>();
        //改变时间字段
        for (int i = 0; i < list.size(); i++) {
            map=list.get(i);
            String time=map.get("begintime").toString().substring(0,10);
            map.put("begintime",time);
        }
        Map<String,Object> pageData=new HashMap<>();
        pageData.put("total",total);
        pageData.put("list",list);
        System.out.println("init postDao");
        System.out.println(pageData.get("list"));
        return pageData;
    }
    //查询热门帖子
    public List<Map<String,Object>> selectHotPost(){
        //计算有多少帖子
        String sql1="select id from post";
        long count =DBHelper.count(sql1);
        //取出点赞最高的10个帖子的id-->size
        final int size=10;
        //热门帖子的id
        int[] hot_id=new int[size];
        JedisPool jp=new JedisPool("127.0.0.1",6379);
        try (Jedis jedis = jp.getResource()) {
            //热门帖子的点赞量
            int[] hot_likesum=new int[size];

            String sql3="select id from post";
            List<Map<String,Object>> ids=DBHelper.selectListMap(sql3);
            for (int i = 0; i < ids.size(); i++) {
                //帖子的id
                String id= "post_"+ids.get(i).get("id");
                //帖子的点赞量
                int likesum;
                try{
                    likesum=Integer.valueOf(jedis.hget(id,"likesum"));
                }catch (NumberFormatException e){
                    likesum=0;
                }
                for (int j = 0; j < size; j++) {
                    //比较，排序出热门帖子
                    if(likesum>hot_likesum[j]){
                        for (int k = size-1; k > j; k--) {
                            hot_likesum[k]=hot_likesum[k-1];
                            hot_id[k]=hot_id[k-1];
                        }
                        hot_likesum[j]=likesum;
                        hot_id[j]=Integer.valueOf(""+ids.get(i).get("id"));
                        break;
                    }
                }
            }
        }
        //查出帖子
        List<Object> params=new ArrayList<>();
        for (int i = 0; i < hot_id.length; i++) {
            params.add(hot_id[i]);
        }
        String sql2="select * from post where id in (?,?,?,?,?,?,?,?,?,?) ";
        List<Map<String,Object>> list= DBHelper.selectListMap(sql2, params.toArray());
        return list;
    }

}
